package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RedisExpireInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RedisExpireInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("authorization");
        // token是空 则提前放行，避免后面报错
        if (StrUtil.isBlank(token)) {
            return true;
        }

        String key = LoginEnum.LOGIN_KEY.getName() + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        // 用户不存在 则提前放行，避免后面报错
        if (userMap.isEmpty()) {
            return true;
        }

        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        UserHolder.saveUser(userDTO);

        stringRedisTemplate.expire(key, 30, TimeUnit.MINUTES);

        return true;
    }

    // 整个请求完成后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
